<?php

namespace app\admin\controller;

use think\Db;
use think\Session;

class Tongji extends Common {
	public function payments()
	{
		$date = input('time');
		$date = $date ? $date : date('Y-m-d', strtotime('-1 day'));
		$this->assign('time', $date);
		$data = action('api/Timing/tongjiPayment', ['date'=>$date, 'return'=>true]);
		$this->assign('data', $data);
		return $this->fetch();
	}

	public function analyzeuser()
	{
	    ini_set('memory_limit', '512M'); // 临时增加到512MB
		$date = input('time');
		$date = input('time')?:'';
		$date = $date ? $date : date('Y-m-d', strtotime('-1 day'));
		$this->assign('time', $date);

		$data = action('api/Timing/tongjiUserData', ['date'=>$date, 'return'=>true]);
		$chatdata = $data['chat'];
		unset($chatdata['count']);
		$counts = ['word'=>0,'audio'=>0,'video'=>0,'ahs'=>0,'vhs'=>0,'at'=>0,'vt'=>0,'ae'=>0,'ve'=>0];
		foreach ($chatdata as $k => $v) {
			if ($k == 'usersexcount') {
				continue;
			}
			foreach ($counts as $key => $value) {
				$counts[$key] += ($v[$key] ?? 0);
			}
		}
		$chatdata['counts'] = $counts;
		$data['chat'] = $chatdata;
		// echo "<pre>";
		// var_dump($data);

        $data['chat_counts'] = [];
        $data['chat_sexs'] = [];
        $chatdatas = Db::name('tongji_user_data')->order('date desc')->limit(14)->column('chat, topup','date');
        foreach ($chatdatas as $key => $value) {
        	$chat = json_decode($value['chat'], true);
        	$data['chat_counts'][$key] = $chat['count']??0;
        	$data['chat_sexs'][$key]['male'] = $chat['usersexcount']['male']??0;
        	$data['chat_sexs'][$key]['female'] = $chat['usersexcount']['female']??0;
        	$data['chat_sexs'][$key]['female_s'] = $chat['usersexcount']['female_s']??0;
        	$data['chat_sexs'][$key]['male_s'] = $chat['usersexcount']['male_s']??0;
        	$data['chat_list_count_en'][$key] = $chat['chat_list_count_en']??0;

        	if ($value['topup']) {
	        	$topup = json_decode($value['topup'], true);
	        	$data['topups'][$key] = $topup;
        	}
        }

        $this->assign('data',$data);
		return $this->fetch();
	}
	public function dynamic()
	{
		$date = input('time');
		$date = $date ? $date : date('Y-m-d', strtotime('-1 day'));
		$this->assign('time', $date);

		$data = action('api/Timing/tongJIDynamic', ['date'=>$date, 'return'=>true]);
        $datas = Db::name('tongji_dynamic')->order('date desc')->limit(14)->column('txt,image,video','date');

        $this->assign('data',$data);
        $this->assign('datas',$datas);
		return $this->fetch();
	}

	public function unreply()
	{
		$date = input('time');
		$date = $date ? $date : date('Y-m-d', strtotime('-1 day'));
		$this->assign('time', $date);
        $data = Db::name('tongji_unreply_records')->where(['date'=>['<=',$date]])->order('date desc')->limit(14)->column('*','date');
		$this->assign('data', $data);
		return $this->fetch();
	}

	public function unreplyList($touids = '', $date = '', $type = 0)
	{
		$where = ['date'=>$date,'touserid'=>['in',$touids]];
		switch (intval($type)) {
			case 0:
				break;
			case 1:
				$where['chat_single'] = ['<>', 0];
				break;
			case 2:
				$where['chat_status'] = ['<>', 2];
				break;
			case 3:
				$where['chat_status'] = 2;
				break;
			case 4:
				$where['chat_isread'] = 1;
				break;
			case 5:
				$where['chat_isread'] = 0;
				break;
			
			default:
				break;
		}

		$search = input('search', '');
		$name = input('name', '');
		if ($search && $name) {
			$where[$search] = $name;
		}

		$data = Db::name('tongji_unreply_list_records')
					->where($where)
					->order('chat_id desc')
					->paginate(_getCachePages(), false, ['query' => request()->param()]);
		$count = Db::name('tongji_unreply_list_records')
					->where($where)
					->count();
		$count_group = Db::name('tongji_unreply_list_records')
					->where($where)
					->group('userid,touserid')
					->count();
        $page = $data->render();

        $this->assign('count', $count);
        $this->assign('count_group', $count_group);
        $this->assign('type', $type);
        $this->assign('touids', $touids);
        $this->assign('date', $date);
        $this->assign('data', $data);
        $this->assign('page', $page);
		return $this->fetch();
	}



	public function accountant($date = '')
	{
		$date = $date ? $date : date('Y-m', strtotime('-1 month'));
		$date_start = date('Y-m-d', strtotime($date));
		$date_end = date('Y-m-d', strtotime('+1 month', strtotime($date)) - 1);
		$this->assign('time', $date);
		$lists = Db::name('tongji_accountant')->whereTime('date', 'between', [$date_start, $date_end])->fetchSql(false)->select(); 

		$data = [];
		foreach ($lists as $key => $value) {
			foreach ($value as $k => $v) {
				if (in_array($k, ['id','date'])) continue;
				if (isset($data[$k])) {
					$data[$k] += floatval($v);
				} else {
					$data[$k] = $v;
				}
			}
		}
		$date_next = date('Y-m-d', strtotime('+1 month', strtotime($date)));
		$amount = Db::name('tongji_total_amount')->where(['date'=>$date_next])->find();
		$data['user_volley_all'] = $amount['user_volley_all'];
		$data['user_score_all'] = $amount['user_score_all'];

		$this->assign('data', $data);
		return $this->fetch();
	}
	public function porno($date = '', $keyword = '', $sex = '')
	{
		$where = [];
		if ($keyword) {
			$where['user_id'] = $keyword;
		} else {
			if (!$date) {
				$date = date('Y-m-d');
			}
			if (!$sex) {
				$sex = 0;
			}
		}
		if ($sex!=='') {
			$sexs = ['男', '女'];
			$where['sex'] = $sexs[$sex];
		}
		$date_start = strtotime($date);
		$date_end = $date_start + 86399;
		$this->assign('sex', $sex);
		$this->assign('date', $date);
		if ($date) {
			$data = Db::name('tongji_lianmai_porno')->where($where)->whereTime('create_time', 'between', [$date_start, $date_end])->order('num desc, create_time desc')->paginate(_getCachePages(), false, ['query' => request()->param()]);
		} else {
			$data = Db::name('tongji_lianmai_porno')->where($where)->order('num desc, create_time desc')->paginate(_getCachePages(), false, ['query' => request()->param()]);
		}
        $page = $data->render();

		$this->assign('keyword', $keyword);
		$this->assign('data', $data);
        $this->assign('page', $page);
		return $this->fetch();
	}


    public function addPornoNum()
    {
        if (request()->isAjax()) {
            $post = input('post.');
            $hour = date('H', strtotime($post['datetime']));
            $min = date('i', strtotime($post['datetime']));
            $privacy_user = $user = Db::name('user')->find($post['user_id']);
            if ($user['reg'] == 2) {
            	$user = Db::name('user')->find($user['authcode']);
            }
            $where = ['user_id'=>$user['id']];
            $datetime = $post['datetime'];
            $create_time = time();
        	if (($hour == 15 && $min >= 30) || $hour > 15) {
        		$where['create_time'] = ['between', [strtotime(date('Y-m-d', strtotime($post['datetime'])) . ' 16:00:00'), strtotime($post['datetime'])+86400]];
        		$create_time = strtotime(date('Y-m-d', strtotime($post['datetime'])+86400) . ' 15:00:00');
        	} else {
        		$where['create_time'] = ['between', [strtotime($post['datetime'])-86400, strtotime(date('Y-m-d', strtotime($post['datetime'])) . ' 14:00:00')]];
        		$create_time = strtotime(date('Y-m-d', strtotime($post['datetime'])-86400) . ' 15:00:00');
        	}
            $today = Db::name('tongji_lianmai_porno')->where($where)->find();
            if (!$today) { //添加数据
                $post['nickname'] = $user['name'];
                $post['sex'] = $user['sex'];
                $post['register_datetime'] = $user['register_datetime'];
                $post['create_time'] = $create_time;
                $post['value'] = $user['shouyi'];
                if ($user['sex'] == '男') {
                	$post['value'] = Db::name('user_data')->where(['user_id'=>$user['id']])->value('topup');
                }
                unset($post['datetime']);
                $res = db('tongji_lianmai_porno')->insert($post);

                if ($res) {
                    $data = ['ret' => '添加成功'];
                } else {
                    $data = ['err' => '添加失败'];
                }
            } else { //修改数据
                $res = db('tongji_lianmai_porno')->where('id', $today['id'])->setInc('num', $post['num']);

                if ($res) {
                    $data = ['ret' => '修改成功'];
                } else {
                    $data = ['err' => '修改失败'];
                }
            }
            if ($res) {
        		$admin = Session::get('admin', 'mmjtAdmin');
            	$adminLog = [
                    'channel' => 3,
                    'toward' => 0,
                    'money' => 0,
                    'admin' => $admin['name'],
                    'user_id' => $user['id'],
                    'content' => '因 ' . ($privacy_user['id']!=$user['id']?'私密号('.$privacy_user['id'].') ':'') . $datetime . ' 涉黄，添加涉黄次数 ' . $post['num']
                ];
                Db::name('admin_logs')->insert($adminLog);
            }
        } else {
            $data = $this->fetch();
        }
        return $data;
    }


    public function blacklistYesterday()
    {
		    	
		// 计算昨天的起始和结束时间戳
		$yesterdayStart = date('Y-m-d H:i:s', strtotime('yesterday midnight'));
		$yesterdayEnd = date('Y-m-d H:i:s', strtotime('yesterday 23:59:59'));

		// 查询昨天被拉黑的用户及其拉黑次数
		$blacklistedUsers = Db::name('blacklist')
		    ->whereTime('addtime','between', [$yesterdayStart, $yesterdayEnd])
		    ->group('user_id')
		    ->having('COUNT(*) > 0')
		    ->field('user_id, COUNT(*) as count')
		    ->cache(86400)
		    ->select();

	    $users = Db::name('user')->where(['id'=>['in', array_column($blacklistedUsers, 'user_id')]])->cache(3600)->column('id,name,is_banned,sex,age', 'id');
	    foreach ($blacklistedUsers as &$value) {
	    	$value['user'] = $users[$value['user_id']]??false;
	    }

		// 对结果按被拉黑次数降序排序
		usort($blacklistedUsers, function ($a, $b) {
		    return $b['count'] <=> $a['count'];
		});

		$this->assign('data',$blacklistedUsers);
		return $this->fetch();
    }

    public function sysHiChatPush($uid = 0)
    {
        if (request()->isAjax()) {
	        $user = Db::name('user')->find($uid);
	        if (!$user) return ['err'=>'用户不存在'];
	        $result = \app\api\model\User::pushchatUnFirst($user, true, true);
	        $result = str_replace('LIMIT 1', '', $result);
	        $sql_result = Db::query($result);
	        $result_nonotin = \app\api\model\User::pushchatUnFirst($user, true, false);
	        $result_nonotin = str_replace('LIMIT 1', '', $result_nonotin);
	        $sql_result_nonotin = Db::query($result_nonotin);


	        $data = [
	        	'count'=>sizeof($sql_result),
	        	'uids'=>implode(',', array_column($sql_result, 'id')),
	        	// 'sql_result'=>$result,
	        	'count_nonotin'=>sizeof($sql_result_nonotin),
	        	'uids_nonotin'=>implode(',', array_column($sql_result_nonotin, 'id')),
	        	// 'sql_result_nonotin'=>$result_nonotin,
	        ];

	        // var_dump($data);
	        return $data;
	    } else {
	    	return $this->fetch();
	    }
    }

	public function userBalance()
	{
		$where = ['income'=>['>', 0]];

		$date = input('date');
		$date = $date ? $date : date('Y-m-d', strtotime('-1 day'));

		$where['date'] = $date;
		$keyword = input('keyword/s','');
		if ($keyword) {
			$where['user_id'] = $keyword;
		}

		if ($date == date('Y-m-d')) {
			$data = db('yaoqing_records')->where(['data'=>0])->whereTime('time', 'today')->group('uid')->field('uid user_id, sum(money) income, DATE_FORMAT(FROM_UNIXTIME(time), "%Y-%m-%d") date')->order('income desc')->cache(60)->paginate(_getCachePages(), false, ['query' => request()->param()]);
		} else {
			$data = db('user_balance')->where($where)->order('income desc')->paginate(_getCachePages(), false, ['query' => request()->param()]);
		}

        $page = $data->render();
        $dataList = $data->all();
        $users = db::name('user')->where(['id'=>['in',array_column($dataList, 'user_id')]])->column('id,name,sex', 'id');
        foreach ($dataList as &$value) {
        	$value['user_name'] = '';
        	$value['user_sex'] = '';
        	if (isset($users[$value['user_id']])) {
	        	$value['user_name'] = $users[$value['user_id']]['name'];
	        	$value['user_sex'] = $users[$value['user_id']]['sex'];
        	}
        }
		$this->assign('data', $dataList);
        $this->assign('page', $page);
		$this->assign('date', $date);
		return $this->fetch();
	}
	/**
     * 统计数据概览
     * @return mixed 渲染统计页面
     */
    public function tongjiNew()
    {
        // 获取前端传递的时间范围参数
        $start = input('param.start', '', 'trim');
        $end = input('param.end', '', 'trim');

        // 保存原始参数到视图
        $this->assign([
            'start' => $start,
            'end' => $end
        ]);

        // 获取需要排除的测试账号ID
        $testMemberIds = $this->testMemberIds();
        // 计算总充值金额
        $totalMoney = $this->calculateTotalRecharge($testMemberIds, 0, $start, $end);
        // 计算会员充值(vip)等类型总金额 会员充值types=6
        $vipMoney = $this->calculateVipRecharge($testMemberIds, 6, $start, $end);
        // 计算新增会员数
        $newMember = $this->calculateNewMember($testMemberIds, $start, $end);
        // 计算总的提现金额
        $totalWithdraw = $this->calculateTotalWithdraw($testMemberIds, 8, $start, $end);
        // 计算总的到账金额
        $totalArrival = $this->calculateTotalWithdrawTo($testMemberIds, 8, $start, $end);
        // 计算总的支付宝提现金额
        $totalWithdraw_zfb = $this->calculateTotalWithdraw($testMemberIds, 1, $start, $end);
        // 计算总的支付宝提现到账金额
        $totalWithdraw_zfb_arrival = $this->calculateTotalWithdrawTo($testMemberIds, 1, $start, $end);
        // 计算总的金币数
        $totalVolley = $this->calculateTotalGold($testMemberIds, 1,$start, $end);
        // 计算总的积分
        $totalScore = $this->calculateTotalGold($testMemberIds, 2,$start, $end);

        // 单独查询测试用户的详细信息（仅用于前端展示）
        $testMemberInfo = Db::name('user')
            ->where('testuser',1)
            ->field('id, name, sex')
            ->order('volley desc')
            ->select();
        //今日时间
        $todayStart = date('Y-m-d 00:00:00');
        $todayEnd = date('Y-m-d 23:59:59');
        //昨日时间
        $yesdayStart=date('Y-m-d 00:00:00', strtotime('-1 day'));
        $yesdayEnd=date('Y-m-d 23:59:59', strtotime('-1 day'));

        //今日相关=》

        //计算总充值金额
        $totalMoney_today = $this->calculateTotalRecharge($testMemberIds, 0, $todayStart, $todayEnd);
        // 计算会员充值(vip)等类型总金额 会员充值types=6
        $vipMoney_today = $this->calculateVipRecharge($testMemberIds, 6, $todayStart, $todayEnd);
        // 计算新增会员数
        $newMember_today = $this->calculateNewMember($testMemberIds, $todayStart, $todayEnd);
        // 计算总的提现金额
        $totalWithdraw_today = $this->calculateTotalWithdraw($testMemberIds, 8, $todayStart, $todayEnd);
        // 计算总的到账金额
        $totalArrival_today = $this->calculateTotalWithdrawTo($testMemberIds, 8, $todayStart, $todayEnd);
        // 计算总的支付宝提现金额
        $totalWithdraw_zfb_today = $this->calculateTotalWithdraw($testMemberIds, 1, $todayStart, $todayEnd);
        // 计算总的支付宝提现到账金额
        $totalWithdraw_zfb_arrival_today = $this->calculateTotalWithdrawTo($testMemberIds, 1, $todayStart, $todayEnd);


        //昨日相关=》

        //计算总充值金额
        $totalMoney_yesday = $this->calculateTotalRecharge($testMemberIds, 0, $yesdayStart, $yesdayEnd);
        // 计算会员充值(vip)等类型总金额 会员充值types=6
        $vipMoney_yesday = $this->calculateVipRecharge($testMemberIds, 6, $yesdayStart, $yesdayEnd);
        // 计算新增会员数
        $newMember_yesday = $this->calculateNewMember($testMemberIds, $yesdayStart, $yesdayEnd);
        // 计算总的提现金额
        $totalWithdraw_yesday = $this->calculateTotalWithdraw($testMemberIds, 8, $yesdayStart, $yesdayEnd);
        // 计算总的到账金额
        $totalArrival_yesday = $this->calculateTotalWithdrawTo($testMemberIds, 8, $yesdayStart, $yesdayEnd);
        // 计算总的支付宝提现金额
        $totalWithdraw_zfb_yesday = $this->calculateTotalWithdraw($testMemberIds, 1, $yesdayStart, $yesdayEnd);
        // 计算总的支付宝提现到账金额
        $totalWithdraw_zfb_arrival_yesday = $this->calculateTotalWithdrawTo($testMemberIds, 1, $yesdayStart, $yesdayEnd);

        /**
         * 计算平台利润（精确到分，最终结果保留两位小数）
         * 利润公式：总充值金额 + VIP充值金额 - 总提现金额 - (金币数/10*97%) - (积分数/10*92%)
         */

        // 1. 确保所有输入为数值类型（避免字符串参与计算）
        $totalMoney = floatval($totalMoney);      // 总充值金额（元）
        $vipMoney = floatval($vipMoney);          // VIP充值金额（元）
        $totalWithdraw = floatval($totalWithdraw);// 总提现金额（元）
        $totalVolley = floatval($totalVolley);    // 金币总数
        $totalScore = floatval($totalScore);      // 积分总数

        // 2. 转换为分进行整数运算（避免浮点数精度问题）
        $totalMoney_fen = intval($totalMoney * 100);       // 总充值金额（分）
        $vipMoney_fen = intval($vipMoney * 100);           // VIP充值金额（分）
        $totalWithdraw_fen = intval($totalWithdraw * 100); // 总提现金额（分）

        // 3. 计算金币和积分成本（分）
        $volleyCost_fen = intval(($totalVolley / 10) * 97);  // 金币成本（分）
        $scoreCost_fen = intval(($totalScore / 10) * 92);    // 积分成本（分）

        // 4. 计算总利润（分）
        $totalProfit_fen = ($totalMoney_fen + $vipMoney_fen)
            - $totalWithdraw_fen
            - $volleyCost_fen
            - $scoreCost_fen;

        // 5. 转换回元，并严格保留两位小数
        $totalProfit = number_format($totalProfit_fen / 100, 2, '.', '');

        // 传递数据到视图
        $this->assign([
            'testMemberInfo' => $testMemberInfo,

            //总数据
            'totalMoney' => $totalMoney,
            'vipMoney' => $vipMoney,
            'newMember' => $newMember,
            'totalWithdraw' => $totalWithdraw,
            'totalArrival' => $totalArrival,
            'totalWithdraw_zfb' => $totalWithdraw_zfb,
            'totalWithdraw_zfb_arrival' => $totalWithdraw_zfb_arrival,
            'totalVolley' => $totalVolley,
            'totalScore' => $totalScore,

            'totalVolley1' => $totalVolley/10,
            'totalScore1' => $totalScore/10,

            //今日数据
            'totalMoney_today' => $totalMoney_today,
            'vipMoney_today' => $vipMoney_today,
            'newMember_today' => $newMember_today,
            'totalWithdraw_today' => $totalWithdraw_today,
            'totalArrival_today' => $totalArrival_today,
            'totalWithdraw_zfb_today' => $totalWithdraw_zfb_today,
            'totalWithdraw_zfb_arrival_today' => $totalWithdraw_zfb_arrival_today,


            //昨日数据
            'totalMoney_yesday' => $totalMoney_yesday,
            'vipMoney_yesday' => $vipMoney_yesday,
            'newMember_yesday' => $newMember_yesday,
            'totalWithdraw_yesday' => $totalWithdraw_yesday,
            'totalArrival_yesday' => $totalArrival_yesday,
            'totalWithdraw_zfb_yesday' => $totalWithdraw_zfb_yesday,
            'totalWithdraw_zfb_arrival_yesday' => $totalWithdraw_zfb_arrival_yesday,
            
            //平台利润
            'totalProfit' => $totalProfit,

        ]);

        // 渲染视图
        return $this->fetch();
    }

    /**
     * 获取需要排除的测试账号ID列表
     * @return array 测试用户ID数组
     */
    private function testMemberIds()
    {
        return Db::name('user')
            ->where('testuser', 1)
            ->whereOr('register_datetime', '<', '2025-05-08 00:00:00')
            ->column('id');
    }

    /**
     * 计算总充值金额
     * @param array $testMemberIds 需要排除的测试用户ID数组
     * @param int $sid 套餐ID（0表示全部）
     * @param string $startTime 开始时间（格式：YYYY-MM-DD HH:MM:SS）
     * @param string $endTime 结束时间（格式：YYYY-MM-DD HH:MM:SS）
     * @return float|int 总充值金额
     */
    private function calculateTotalRecharge($testMemberIds, $sid = 0, $startTime = '', $endTime = '')
    {
        $query = Db::name('topup')
            ->where('fk_userid', 'not in', $testMemberIds)
            ->where('state', 1); // 状态1=已支付

        if ($sid) {
            $query->where('sid', $sid);
        }

        // 直接使用字符串比较（datetime类型）
        if (!empty($startTime)) {
            $query->where('addtime', '>=', $startTime);
        }
        if (!empty($endTime)) {
            $query->where('addtime', '<=', $endTime);
        }

        return $query->sum('price');
    }

    /**
     * 计算会员充值(vip)等类型总金额
     * @param array $testMemberIds 需要排除的测试用户ID数组
     * @param int $types 订单类型（6表示会员充值）
     * @param string $startTime 开始时间（格式：YYYY-MM-DD）
     * @param string $endTime 结束时间（格式：YYYY-MM-DD）
     * @return float|int 会员充值总金额
     */
    private function calculateVipRecharge($testMemberIds, $types = 0, $startTime = '', $endTime = '')
    {
        $query = Db::name('order_common')
            ->where('user_id', 'not in', $testMemberIds)
            ->where('status', 1); // 状态1=已支付

        if ($types) {
            $query->where('types', $types);
        }

        // 转换为时间戳（与数据库字段类型匹配）
        if (!empty($startTime)) {
            $query->where('create_time', '>=', strtotime($startTime));
        }
        if (!empty($endTime)) {
            $query->where('create_time', '<=', strtotime($endTime));
        }

        return $query->sum('money');
    }

    /**
     * 计算新增会员数
     * @param array $testMemberIds 需要排除的测试用户ID数组
     * @param string $startTime 开始时间（格式：YYYY-MM-DD HH:MM:SS）
     * @param string $endTime 结束时间（格式：YYYY-MM-DD HH:MM:SS）
     * @return int 新增会员数量
     */
    private function calculateNewMember($testMemberIds, $startTime = '', $endTime = '')
    {
        $query = Db::name('user')
            ->where('id', 'not in', $testMemberIds)
            ->where('reg', 1);    // 只统计有效会员

        // 直接使用字符串比较（datetime类型）
        if (!empty($startTime)) {
            $query->where('register_datetime', '>=', $startTime);
        }
        if (!empty($endTime)) {
            $query->where('register_datetime', '<=', $endTime);
        }

        return $query->count();
    }

    /**
     * 计算总的提现金额
     * @param array $testMemberIds 需要排除的测试用户ID数组
     * @param int $paymethod 提现方式（0-微信 1-支付宝 2-银行卡 8-全部）
     * @param string $startTime 开始时间（格式：YYYY-MM-DD）
     * @param string $endTime 结束时间（格式：YYYY-MM-DD）
     * @return float|int 提现总金额
     */
    private function calculateTotalWithdraw($testMemberIds, $paymethod = 8, $startTime = '', $endTime = '')
    {
        $query = Db::name('withdraw')
            ->where('userid', 'not in', $testMemberIds)
            ->where('state', 1); // 状态1=审核成功

        if ($paymethod !== 8) {
            $query->where('paymethod', $paymethod);
        }

        // 转换为时间戳（与数据库字段类型匹配）
        if (!empty($startTime)) {
            $query->where('create_time', '>=', strtotime($startTime));
        }
        if (!empty($endTime)) {
            $query->where('create_time', '<=', strtotime($endTime));
        }

        return $query->sum('money');
    }

    /**
     * 计算总的提现到账金额
     * @param array $testMemberIds 需要排除的测试用户ID数组
     * @param int $paymethod 提现方式（0-微信 1-支付宝 2-银行卡 8-全部）
     * @param string $startTime 开始时间（格式：YYYY-MM-DD）
     * @param string $endTime 结束时间（格式：YYYY-MM-DD）
     * @return float|int 提现到账总金额
     */
    private function calculateTotalWithdrawTobak($testMemberIds, $paymethod = 8, $startTime = '', $endTime = '')
    {
        $query = Db::name('withdraw')
            ->where('userid', 'not in', $testMemberIds)
            ->where('state', 1); // 状态1=审核成功

        if ($paymethod !== 8) {
            $query->where('paymethod', $paymethod);

            // 微信/支付宝需要额外检查 txstate=1
            if ($paymethod == 0 || $paymethod == 1) {
                $query->where('txstate', 1);
            }
        } else {
            // 全部支付方式时，同时统计：(微信/支付宝 且 txstate=1) 或 (银行卡)
            $query->where(function($q) {
                $q->where(function($qq) {
                    $qq->where('paymethod', 'in', [0, 1])->where('txstate', 1);
                })->whereOr('paymethod', 2);
            });
        }

        // 转换为时间戳（与数据库字段类型匹配）
        if (!empty($startTime)) {
            $query->where('create_time', '>=', strtotime($startTime));
        }
        if (!empty($endTime)) {
            $query->where('create_time', '<=', strtotime($endTime));
        }

        return $query->sum('money');
    }
    
    private function calculateTotalWithdrawTo($testMemberIds, $paymethod = 8, $startTime = '', $endTime = '')
    {
        $query = Db::name('withdraw')
            ->where('userid', 'not in', $testMemberIds)
            ->where('state', 1) // 状态1=审核成功
            ->where('txstate', 1); // 统一使用txstate=1作为到账成功标准

        if ($paymethod != 8) {
            $query->where('paymethod', $paymethod);
        }

        // 转换为时间戳（与数据库字段类型匹配）
        if (!empty($startTime)) {
            $query->where('create_time', '>=', strtotime($startTime));
        }
        if (!empty($endTime)) {
            $query->where('create_time', '<=', strtotime($endTime));
        }

        return $query->sum('money');
    }

    /**
     * 计算现存金币数和积分总数
     * @param array $testMemberIds 需要排除的测试用户ID数组
     * @param int $type 金币类型（1-金币 2-积分）
     * @param string $startTime 开始时间（格式：YYYY-MM-DD）
     * @param string $endTime 结束时间（格式：YYYY-MM-DD）
     * @return float|int 提现到账总金额
     */
    private function calculateTotalGold($testMemberIds, $type = 1)
    {
        $query = Db::name('user')
            ->where('id', 'not in', $testMemberIds);

        if ($type == 1) {
            $query->where('volley', '>', 0);
        } elseif ($type == 2) {
            $query->where('score', '>', 0);
        }
        return $query->sum($type == 1 ? 'volley' : 'score');
    }

}